/**
 * Created by huanggw on 2015/11/6.
 */

var array = document.getElementById("array"); //箭头
var listC = document.getElementById("listContainer");
var toggle = document.getElementById("switch");
var gatelist = document.getElementById("gatelist");
var footer = document.getElementById("footer");
var mapContainer = document.getElementById('mapContainer');
var map2dContainer = document.getElementById("map2d");
var storyContainer = document.getElementById("story");
var commentContainer = document.getElementById("commentContainer");
var commentContent = document.getElementById("commentContent");
var commentSubmit = document.getElementById("commentSubmit");
var like = document.getElementById("like");

toggle.onclick = function() {
    if(document.getElementById("toggle").checked) {
        listC.style.top = "110%";
    }
};

var panorama = new BMap.Panorama('mapContainer');
panorama.setOptions({linksControl: false});
panorama.setOptions({navigationControl: false});

var panoramaService = new BMap.PanoramaService();

var mainApp = angular.module('schoolgate',['ui.router', 'tm.pagination', 'ngAnimate']);

mainApp.run(['$rootScope', '$state', '$stateParams',
    function ($rootScope,   $state,   $stateParams) {
        // add references to $state and $stateParams to the $rootScope
        // so that you can access them from any scope within your applications
        $rootScope.$state = $state;
        $rootScope.$stateParams = $stateParams;
        //console.log($rootScope.$state)
    }
]);

mainApp.controller('mainCtrl', function($scope, $timeout) {
    $scope.routers = [
        {name: "注册", view: "regist"},
        {name: "登录", view: "login"}
    ];
    $scope.city = "城市"; //当前城市
    $scope.school = "学校"; //当前学校
    $scope.campus = "校区"; //当前校区
    $scope.gate = "校门"; //当前校门
    $scope.list = [];
    $scope.schoolinfo = null; //当前学校信息
    $scope.campusinfo = null; //当前校区信息
    $scope.gateinfo = null; //当前校门信息
    $scope.schoolselected = 0;
    $scope.campusselected = 0;
    $scope.type = 1; //当前选项
    $scope.id = null; //当前id
    $scope.story = "";
    $scope.commentContent = '';
    $scope.commentsAll = []; //当前校门评论
    $scope.comments = []; //当前页评论
    $scope.username = 'Guest';
    $scope.likeStatus = 0;

    $scope.getlike = function() {
        var url = encodeURI(host+"/like/?city="+$scope.city+"&school="+$scope.school+"&campus="+$scope.campus+"&gate="+$scope.gate);
        xhr.open("GET", url, true);
        xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
        xhr.onreadystatechange=function(){
            if(xhr.readyState==4){
                if(xhr.status==200){
                    $timeout(function(){
                        //console.log(JSON.parse(xhr.responseText))
                        $scope.likenum = JSON.parse(xhr.responseText).likenum;
                        //获取点赞信息
                        $scope.getLikeInfo();
                    }, 10)
                }
            }
        }
        xhr.send();
    }

    $scope.like = function() {
        if(!$scope.loginUser) {alert("还未登录，请先登录！"); return;}
        if($scope.likeStatus == 1) {alert("您已经赞过啦，去逛逛别的校门吧！"); return;}
        var url = host+"/like";
        var obj = {
            city: $scope.city,
            school: $scope.school,
            campus: $scope.campus,
            gate: $scope.gate,
            time: new Date().getMonth()+1+"月"+new Date().getDate()+"日 "+new Date().getHours()+":"+new Date().getMinutes(),
            user: $scope.loginUser
        }
        xhr.open("POST", url, true);
        xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
        xhr.onreadystatechange=function(){
            if(xhr.readyState==4){
                if(xhr.status==200){
                    if(JSON.parse(xhr.responseText).loginStatus == 0) {
                        alert("会话过期，请重新登陆登录。")
                        window.location.href = '/login';
                        return;
                    }
                    $timeout(function(){
                        //console.log(JSON.parse(xhr.responseText))
                        $scope.likenum = JSON.parse(xhr.responseText).likenum;
                        //获取点赞信息
                        $scope.getLikeInfo();
                    }, 10)
                }
            }
        }
        xhr.send(JSON.stringify(obj));
    }

    $scope.commentSubmit = function() {
        if(!$scope.commentContent) {alert("请输入评论！"); return;};
        if(!$scope.loginUser) {alert("还未登录，请先登录！"); return;}
        var url = host+"/comment";
        var obj = {
            city: $scope.city,
            school: $scope.school,
            campus: $scope.campus,
            gate: $scope.gate,
            comment: $scope.commentContent,
            time: new Date().getMonth()+1+"月"+new Date().getDate()+"日 "+new Date().getHours()+":"+new Date().getMinutes(),
            user: $scope.loginUser
        }
        xhr.open("POST", url, true);
        xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
        //http://schoolgate.oschina.mopaasapp.com/
        xhr.onreadystatechange=function(){
            if(xhr.readyState==4){
                if(xhr.status==200){
                    if(JSON.parse(xhr.responseText).loginStatus == 0) {
                        alert("会话过期，请重新登陆登录。");
                        window.location.href = '/login';
                        return;
                    }
                    $timeout(function(){
                        $scope.commentsAll = JSON.parse(xhr.responseText);
                        //console.log($scope.commentsAll);
                        //var page = Math.ceil($scope.commentsAll.length/$scope.conf.itemsPerPage)
                        $scope.setPagination($scope.commentsAll.length, 1);
                        $scope.getCommentByPage(1);
                        $scope.commentContent = '';
                    },20)
                }
                else {

                }
            }
        }
        xhr.send(JSON.stringify(obj));
    }

    $scope.getComment = function() {
        var url = encodeURI(host+"/comment/?city="+$scope.city+"&school="+$scope.school+"&campus="+$scope.campus+"&gate="+$scope.gate);
        xhr.open("GET", url, true);
        //http://schoolgate.oschina.mopaasapp.com/
        xhr.onreadystatechange=function(){
            if(xhr.readyState==4){
                if(xhr.status==200){
                    $timeout(function(){
                            $scope.commentsAll = JSON.parse(xhr.responseText);
                            $scope.setPagination($scope.commentsAll.length, 1);
                            $scope.getCommentByPage(1);
                            $scope.getlike();
                        }, 50
                    )
                }
            }
        }
        xhr.send();
    }

    $scope.getCommentByPage = function (page) {
        var start = (page-1)*15;
        var end = page*15;
        if(page == $scope.paginationConf.numberOfPages) {
            end = $scope.commentsAll.length;
        }
        $scope.comments = $scope.commentsAll.slice(start, end);
        //console.log($scope.comments)
    }

    $scope.setPagination = function(total, page) {
        //pagination
        $scope.paginationConf = {
            currentPage: page,
            totalItems: total,
            itemsPerPage: 15,
            pagesLength: 5,
            perPageOptions: [10, 20, 30, 40, 50],
            onChange: function(){
                $scope.getCommentByPage($scope.paginationConf.currentPage)
            }
        };
    }

    $scope.getCityInfo  = function() {
        var url = host+"/getinfo/?citylist=1"
        xhr.open("GET", url, true);
        //http://schoolgate.oschina.mopaasapp.com/
        xhr.onreadystatechange=function(){
            if(xhr.readyState==4){
                if(xhr.status==200){
                    $scope.list = [];
                    var data = JSON.parse(xhr.responseText);
                    $scope.cityinfo = data;
                    //console.log(data)
                    var str = JSON.parse(xhr.responseText.replace(/cityname/g, 'name'));
                    $timeout(function(){
                            $scope.list = str;
                            //$scope.setVal(0); //设定为第一个城市
                            //$scope.getSchoolInfo();
                        }, 50
                    )
                }
            }
        }
        xhr.send();
    }

    $scope.setCity = function() {
        $scope.type = 1;
        $scope.getCityInfo();
        //设置箭头位置
        array.style.left = "calc(50% - 160px)";
        listC.style.top = "40px";
    }

    $scope.getSchoolInfo = function() {
        var url = encodeURI(host+"/getinfo/?city="+$scope.city);
        xhr.open("GET", url, true); //getinfo?num=32&num1=13&type=add
        xhr.onreadystatechange=function(){
            if(xhr.readyState==4){
                if(xhr.status==200){
                    $scope.list = [];
                    //获取信息初始化
                    var data = JSON.parse(xhr.responseText);
                    $scope.schoolinfo = data;
                    $scope.school = data[0].schoolname;
                    $scope.story = "";
                    var str = JSON.parse(xhr.responseText.replace(/schoolname/g, 'name'));
                    $timeout(function(){
                        $scope.list = str
                        }, 20
                    )
                }
            }
        }
        xhr.send();
    }

    $scope.setSchool = function() {
        $scope.type = 2;
        $scope.getSchoolInfo();
        //设置箭头位置
        array.style.left = "calc(50% - 60px)";
        listC.style.top = "40px";
    }

    $scope.getCampusInfo = function() {
        var url = encodeURI(host+"/getinfo/?city="+$scope.city+"&school="+$scope.school);
        xhr.open("GET", url, true); //getinfo?num=32&num1=13&type=add
        xhr.onreadystatechange=function(){
            if(xhr.readyState==4){
                if(xhr.status==200){
                    $scope.list = [];
                    var data = JSON.parse(xhr.responseText);
                    $scope.campusinfo = data;
                    $scope.campus = data[0].campusname;
                    var str = JSON.parse(xhr.responseText.replace(/campusname/g, 'name'));
                    $timeout(function(){
                            $scope.list = str;
                        }, 20
                    )
                }
            }
        }
        xhr.send();
    }

    $scope.setCampus = function() {
        $scope.type = 3;
        $scope.getCampusInfo();
        //设置箭头位置
        array.style.left = "calc(50% + 40px)";
        listC.style.top = "40px";
    }

    $scope.getGateInfo = function() {
        var url = encodeURI(host+"/getinfo/?city="+$scope.city+"&school="+$scope.school+"&campus="+$scope.campus);
        xhr.open("GET", url, true); //getinfo?num=32&num1=13&type=add
        xhr.onreadystatechange=function(){
            if(xhr.readyState==4){
                if(xhr.status==200){
                    $scope.list = [];
                    var data = JSON.parse(xhr.responseText);
                    $scope.gateinfo = data;
                    $scope.gate = data[0].gatename;
                    var str = JSON.parse(xhr.responseText.replace(/gatename/g, 'name'));
                    $timeout(function(){
                            $scope.list = str;
                        }, 20
                    )
                }
            }
        }
        xhr.send();
    }

    $scope.setGate = function() {
        $scope.type = 4;
        $scope.getGateInfo();
        //设置箭头位置
        array.style.left = "calc(50% + 140px)";
        listC.style.top = "40px";
    }

    $scope.setVal = function(num) {
        if($scope.type == 1) {
            $scope.city = $scope.cityinfo[num].cityname;
        }
        else if($scope.type == 2){
            $scope.school = $scope.schoolinfo[num].schoolname;
            $scope.schoolselected = num;
        }
        else if($scope.type == 3){
            $scope.campus = $scope.campusinfo[num].campusname;
            $scope.campusselected = num;
        }
        else if($scope.type == 4){
            $scope.gate = $scope.gateinfo[num].gatename;
            listC.style.top = "110%";
            toggle.checked = false;
            if($scope.gateinfo[num].alsoname) {
                $scope.current = $scope.school+$scope.campus+$scope.gate+"("+$scope.gateinfo[num].alsoname+")";
            }
            else {
                $scope.current = $scope.school+$scope.campus+$scope.gate
            }
            if($scope.gateinfo[num].story) {
                $scope.story = $scope.gateinfo[num].story;
                storyContainer.style.left = "20px";
                $timeout(function() {
                    storyContainer.style.left = "-300px";
                }, 30000);
            }
            else {
                storyContainer.style.left = "-300px";
            }
            $scope.setView($scope.gateinfo[num].pid, $scope.gateinfo[num].heading,
                $scope.gateinfo[num].pitch);
            //更换id
            //$scope.id = $scope.gateinfo[num].id;

            //评论
            $scope.getComment();
        }
    }

    $scope.setValDirect = function(num) {
        //直接设置
        $scope.type = 4;
        $scope.setVal(num);
    }

    //var tanslateCallback =
    $scope.setView = function(id, heading, pitch) {
        //2维地图
        panoramaService.getPanoramaById(id, function(data) {
            //console.log(data.position);
            var point = new BMap.Point(data.position.lng, data.position.lat);
            var map = new BMap.Map("map2d",{minZoom:10,maxZoom:25});
            map.centerAndZoom(point, 18);
            var marker = new BMap.Marker(point);
            map.addOverlay(marker);
        })
        //全景地图
        panorama.setId(id);
        $timeout(function(){
            panorama.setPov({heading: heading, pitch: pitch, zoom: 1.31});
        },200);
    }

    $scope.confirmTip = function() {
        document.getElementById("tip").style.left = "-400px";
    }

    $scope.geo = function() {
        //定位
        var geolocation = new BMap.Geolocation();
        //逆解析城市名
        var geoc = new BMap.Geocoder();
        geolocation.getCurrentPosition(function(r){
            if(this.getStatus() == BMAP_STATUS_SUCCESS){
                //console.log('您的位置：'+r.point.lng+','+r.point.lat);
                var point = new BMap.Point(r.point.lng, r.point.lat);
                geoc.getLocation(point, function(rs){
                    var addComp = rs.addressComponents;
                    //console.log(addComp.province + ", " + addComp.city + ", " + addComp.district + ", " + addComp.street + ", " + addComp.streetNumber);

                });
            }
            else {
                console.log('failed'+this.getStatus());
            }
        },{enableHighAccuracy: true})
    }

    $scope.full = function() {
        if(document.documentElement.requestFullscreen) {
            document.documentElement.requestFullscreen();
        } else if(document.documentElement.mozRequestFullScreen) {
            document.documentElement.mozRequestFullScreen();
        } else if(document.documentElement.webkitRequestFullscreen) {
            document.documentElement.webkitRequestFullscreen();
        } else if(document.documentElement.msRequestFullscreen) {
            document.documentElement.msRequestFullscreen();
        }
    }

    var _2dview = 0;
    $scope.mapview = function() {
        //$scope._2dview = $scope._2dview == 1? 0 : 1;
        if(_2dview == 0) {
            map2dContainer.style.top = "0px";
            _2dview = 1;
        }else {
            map2dContainer.style.top = "100%";
            _2dview = 0;
        }
    }

    var on = 0;
    $scope.showgatelist = function(num) {
        on = num;
        if(num == 0) {
            //footer.style.borderLeft ="1px solid rgba(100, 100, 100, 0.5)";
        }
        //gatelist.style.right = "104px";
        var n = $scope.gateinfo.length;
        gatelist.style.bottom = "30px";
        gatelist.style.opacity = 1;
        commentContainer.style.bottom = 31*n + 30 + "px";
    }

    $scope.hidegatelist = function() {
        /*if(num == 0) {
         footer.style.background = "rgba(39, 39, 39, 0.3)"
         $timeout(function(){
         if(on == 1) return false;
         gatelist.style.bottom = "-400px";
         }, 2000)
         }
         else {
         gatelist.style.bottom = "-400px";
         }*/
        var n = $scope.gateinfo.length;
        gatelist.style.bottom = -31*n + 30 + "px";
        gatelist.style.opacity = 0;
        commentContainer.style.bottom = "30px";
    }

    $scope.hidelistC = function() {
        listC.style.top = "110%";
    }

    var _commentview = 0;
    $scope.commentview = function() {
        if(_commentview == 0) {
            _commentview = 1;
            commentContainer.style.right = "0px";
            commentSubmit.style.right = "7px";
            commentContent.style.right = "7px";

            $scope.getComment();
        }
        else{
            _commentview = 0;
            commentContainer.style.right = "-400px";
            commentSubmit.style.right = "-400px";
            commentContent.style.right = "-400px";
        }
    }

    $scope.hehe = function() {
        console.log("hh")
    }

    //获取登录信息
    $scope.getLoginInfo = function() {
        var url = host+"/islogin"
        xhr.open("GET", url, true);
        //http://schoolgate.oschina.mopaasapp.com/
        xhr.onreadystatechange=function(){
            if(xhr.readyState==4){
                if(xhr.status==200){
                    var data = JSON.parse(xhr.responseText)
                    $timeout(function(){
                            $scope.loginStatus = data.loginStatus;
                            $scope.loginUser = data.username;
                            if(data.loginStatus == 0) return;
                            $scope.routers = [
                                {name: "登出", view: "logout"},
                                {name: data.username, view: "home/?user="+data.username}
                            ];
                        }, 10
                    )
                }
            }
        }
        xhr.send();
    }

    //获取当前用户的点赞信息
    $scope.getLikeInfo = function() {
        if($scope.loginUser) {
            var url = encodeURI(host+"/likestatus/?city="+$scope.city+"&school="+$scope.school+"&campus="+
                $scope.campus+"&gate="+$scope.gate+"&user="+$scope.loginUser);
            xhr.open("GET", url, true);
            xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
            xhr.onreadystatechange=function(){
                if(xhr.readyState==4){
                    if(xhr.status==200){
                        $timeout(function(){
                            $scope.likeStatus = JSON.parse(xhr.responseText).likeStatus;
                            console.log(JSON.parse(xhr.responseText))
                        }, 20)
                    }
                }
            }
            xhr.send();
        }
    }

    //初始化
    $scope.current = "上海交通大学闵行校区东门";
    $scope.city = "上海";
    $scope.school = "上海交通大学";
    $scope.campus = "闵行校区";
    $scope.gate = "东门";
    $scope.type = 4;
    $scope.gateinfo = [
        {"gatename":"东门","pid":"01000300001309181348482385D","heading":247,"pitch": 1},
        {"gatename":"思源门","pid":"01000300001309271133460215C","heading":342,"pitch":1},
        {"gatename":"东南一门","alsoname":"凯旋门","pid":"01000300001309201158390965D","heading":343,"pitch":-3},
        {"gatename":"北一门","pid":"01000300001309271053335345C","heading":172,"pitch":-1}
    ];
    //从服务器获取数据
    $scope.setPagination(0);
    $scope.geo();
    $scope.setView("01000300001309181348482385D", 247, 1, 1.31);
    $scope.getLoginInfo();
})

mainApp.config([
    '$compileProvider',
    function( $compileProvider )
    {
        $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|chrome-extension|blob:chrome-extension):/);
        // Angular before v1.2 uses $compileProvider.urlSanitizationWhitelist(...)
        $compileProvider.imgSrcSanitizationWhitelist(/^\s*(https?|ftp|file|chrome-extension):|data:image\//)
    }
])
